import React, { Component } from 'react';
import { connect } from 'dva';
import {
  Table,
  Tree,
  Input,
  Select,
  Button,
  Icon,
  Pagination,
  Modal,
  Switch,
  message,
  Form,
  Radio,
} from 'antd';
import styles from '../userManage/index.css';
import { Dispatch, AnyAction } from 'redux';
import { produce, Draft } from 'immer';
import { DEFAULT_PAGE_NUM, DEFAULT_PAGE_SIZE } from '@/const';
import {
  userStatus,
  deleteMenu,
  addMenu,
  editorMenu,
  menuList,
  queryEditorMenu,
} from '@/services/systemDevice';
import { DeviceListsItem } from '@/models/connect';
import { isMenuVisible } from './../../../utils/utils';
import { FormComponentProps } from 'antd/es/form';
import _ from 'lodash';
const { Option } = Select;
const { TextArea } = Input;
const { TreeNode } = Tree;
interface menuPsops extends FormComponentProps {
  loading: boolean;
  dispatch: Dispatch<AnyAction>;
  // deptList?: DeviceListsItem;
  form: FormComponentProps['form'];
}
interface menuManager {
  pageTotal: number;
  filterQueryParams: any;
  userStatus: any;
  params: any;
  showModel: boolean;
  menuId: any;
  title: any;
  isTrue: boolean;
  isAdd: boolean;
  isChecked: boolean;
  addChecked: boolean;
  menuList: any;
  isMenuShow: boolean;
  selectedKeys: any;
  expandedKeys: any;
  autoExpandParent: boolean;
  parentName: any;
  menuName: any;
  expandedRowsKeys: any;
  keys: any;
  keysArr: any;
  parentMenu: any;
}
// @connect(({ loading, systemDevice }: any) => ({
//     loading: loading.effects['systemDevice/userList'],
//     deptList: systemDevice.deptList
// }))
class menuManage extends Component<menuPsops, menuManager> {
  state: menuManager = {
    userStatus: [], //用户状态
    pageTotal: 0,
    filterQueryParams: {
      //   pageNum: 1,
      //   pageSize: 10,
      menuName: '',
      visible: '',
    },
    params: {
      dictType: 'sys_menu_status',
    },
    showModel: false,
    menuId: [],
    title: '',
    isTrue: false,
    isAdd: true,
    isChecked: true,
    addChecked: true,
    menuList: [],
    isMenuShow: false,
    selectedKeys: [],
    expandedKeys: [],
    autoExpandParent: true, //自动展开父级
    parentName: '',
    menuName: '',
    expandedRowsKeys: [],
    keys: [],
    keysArr: [],
    parentMenu: [],
  };
  async componentWillMount() {
    const { dispatch } = this.props;
    const [err, data] = await userStatus(this.state.params);
    if (!err) {
      this.setState(
        produce((draft: Draft<menuManager>): void => {
          draft.userStatus = data;
        }),
      );
    }
    // if (isMenuVisible('96')) {
    isMenuVisible('system:menu:queryByList') && this.handleFilterQuery();
    // }
  }

  handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    // 菜单名称
    e.persist();
    this.setState(
      produce((draft: Draft<menuManager>): void => {
        draft.filterQueryParams.menuName = e.target.value;
      }),
    );
  };

  handleChangeStatus = (e: string) => {
    // 菜单状态
    this.setState(
      produce((draft: Draft<menuManager>): void => {
        draft.filterQueryParams.visible = e;
      }),
    );
  };

  // 页码变化
  handlePageChange: (pageNum: number, pageSize: number | undefined) => void = pageNum => {
    this.setState(
      produce((draft: Draft<menuManager>): void => {
        draft.filterQueryParams.pageNum = pageNum;
      }),
      () => isMenuVisible('system:menu:queryByList') && this.handleFilterQuery(),
    );
  };
  handleFilterQuery = async () => {
    // 搜索
    const [err, data] = await menuList(this.state.filterQueryParams);
    if (!err) {
      this.setState(
        produce((draft: Draft<menuManager>): void => {
          draft.expandedRowsKeys = [];
          draft.menuList = data;
        }),
      );
    }
  };
  handleSure = async () => {
    // 确认删除
    const [err, data] = await deleteMenu({ menuId: this.state.menuId });
    if (!err) {
      this.setState(
        produce((draft: Draft<menuManager>): void => {
          draft.isTrue = false;
        }),
      );
      message.info('删除成功');
    } else {
      this.setState(
        produce((draft: Draft<menuManager>): void => {
          draft.isTrue = false;
        }),
      );
    }
    isMenuVisible('system:menu:queryByList') && this.handleFilterQuery();
  };
  handleSigDelete = (record: any) => {
    // 删除
    this.setState(
      produce((draft: Draft<menuManager>): void => {
        draft.menuId = record.menuId;
      }),
    );
    this.setState(
      produce((draft: Draft<menuManager>): void => {
        draft.title = '确定要删除选中数据吗？';
        draft.isTrue = true;
      }),
    );
  };
  handleAddDept = async () => {
    //新增
    this.state.parentName = '';
    const [err, data] = await menuList({});
    if (!err) {
      this.setState(
        produce((draft: Draft<menuManager>): void => {
          draft.showModel = true;
          draft.isAdd = true;
          draft.parentMenu = data;
        }),
      );
    }
  };
  handleSubmit = (e: any) => {
    // 确认新增
    // e.preventDefault();
    this.props.form.validateFields((err, values) => {
      values.parentId = this.state.selectedKeys.join(','); // 上级菜单 id
      values.visible = values.visible ? '0' : '1';
      if (!err) {
        this.handleInsert(values);
      }
    });
  };
  //修改
  handleEditor = async (record: any) => {
    const [error, datas] = await menuList({});
    if (!error) {
      this.setState(
        produce((draft: Draft<menuManager>): void => {
          draft.parentMenu = datas;
        }),
      );
    }
    this.setState({
      // 上级菜单的选中效果
      selectedKeys: [record.parentId],
    });
    const [err, data] = await queryEditorMenu({ menuId: record.menuId });
    this.setState(
      produce((draft: Draft<menuManager>): void => {
        draft.isAdd = false;
        draft.isChecked = record.visible === '0' ? true : false;
        draft.showModel = true;
        draft.parentName = data.parentName;
        draft.keysArr = record.parentId;
      }),
    );
    this.props.form.setFieldsValue({
      parentId: record.parentId,
      menuId: record.menuId,
      menuType: record.menuType,
      menuName: record.menuName,
      path: record.path,
      perms: record.perms,
      orderNum: record.orderNum,
      // parentName: data.parentName,
      visible: record.visible == 0 ? true : false,
    });
  };
  handleInsert = async values => {
    // 确认插入(判断新增和修改)
    if (this.state.isAdd) {
      const [err, data] = await addMenu(values);
      if (!err) {
        this.setState(
          produce((draft: Draft<menuManager>): void => {
            draft.showModel = false;
          }),
        );
        message.info('新增成功');
        this.props.form.resetFields();
      }
    } else {
      const [err, data] = await editorMenu(values);
      if (!err) {
        this.setState(
          produce((draft: Draft<menuManager>): void => {
            draft.showModel = false;
          }),
        );
        message.info('修改成功');
        this.props.form.resetFields();
      }
    }
    isMenuVisible('system:menu:queryByList') && this.handleFilterQuery();
  };
  onSwitchChange = (checked: any) => {
    // 切换选中状态
    this.setState({ isChecked: checked });
    this.setState({ addChecked: checked });
  };
  menuParent = () => {
    //上级菜单Modal窗口显示
    this.setState(
      produce((draft: Draft<menuManager>): void => {
        draft.isMenuShow = true;
      }),
    );
  };

  /**
   * 展开树
   */
  handleUnfold = () => {
    //展开折叠
    const list = this.state.menuList;
    const keys: any = [];
    this.upfoldAllMenu(list, keys);
    this.setState({ expandedRowsKeys: keys });
  };

  upfoldAllMenu = (menus: any, keys: any) => {
    menus.forEach((menu: any) => {
      keys.push(menu.menuId);

      if (menu.children) {
        this.upfoldAllMenu(menu.children, keys);
      }
    });
  };

  /**
   * 折叠树
   */
  handleUpTree = () => {
    this.setState({
      expandedRowsKeys: [],
    });
  };

  /**
   * 表格展开折叠事件
   */
  handleOnExpand = (expanded: any, record: any) => {
    let keys = [].concat(this.state.expandedRowsKeys);
    let id: any = record.menuId;
    if (expanded) {
      keys.push(id);
    } else {
      let index = keys.indexOf(id);
      if (index > -1) {
        keys.splice(index, 1);
      }

      if (record.children) {
        this.upChildren(record.children, keys);
      }
    }
    this.setState({
      expandedRowsKeys: keys,
    });
  };
  /**
   * 收缩所有子节点----递归
   */
  upChildren = (children: any, keys: any) => {
    let index = 0;
    children.forEach((child: any) => {
      index = keys.indexOf(child.menuId);
      if (index > -1) {
        keys.splice(index, 1);
      }

      if (child.children) {
        this.upChildren(child.children, keys);
      }
    });
  };
  onExpand = (expandedKeys: any) => {
    this.setState({
      expandedKeys,
      autoExpandParent: false,
    });
  };
  onSelect = (selectedKeys: any, info: any) => {
    // 获取父级菜单选中的id和名称
    this.setState({ selectedKeys });
    this.setState({ menuName: info.node.props.title });
  };

  handleMenu = () => {
    //确认父级菜单
    this.setState({ parentName: this.state.menuName });
    this.setState({ isMenuShow: false });
  };

  renderTreeNodes = (data: Array<any>) =>
    data.map(item => {
      if (item.children) {
        return (
          <TreeNode title={item.menuName} key={item.menuId} dataRef={item}>
            {this.renderTreeNodes(item.children)}
          </TreeNode>
        );
      }
      return <TreeNode key={item.menuId} {...item} />;
    });
  columns: any = [
    {
      title: '菜单名称',
      dataIndex: 'menuName',
      key: 'menuName',
    },
    {
      title: '排序',
      dataIndex: 'orderNum',
      key: 'orderNum',
    },
    // {
    //   title: '请求地址',
    //   dataIndex: 'path',
    //   key: 'path',
    // },
    {
      title: '类型',
      dataIndex: 'menuType',
      key: 'menuType',
      render: (text: any, record: any) => {
        return record.menuType === 'M' ? (
          <span>目录</span>
        ) : record.menuType === 'C' ? (
          <span>菜单</span>
        ) : (
          <span>按钮</span>
        );
      },
    },
    // {
    //   title: '可见',
    //   dataIndex: 'visible',
    //   key: 'visible',
    //   render: (text: any, record: any) => {
    //     return record.visible == 0 ? (
    //       <span style={{ color: 'rgb(69, 235, 167)' }}>显示</span>
    //     ) : (
    //       <span style={{ color: '#cb3203' }}>隐藏</span>
    //     );
    //   },
    // },
    {
      title: '权限表示',
      dataIndex: 'perms',
      key: 'perms',
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      key: 'createTime',
    },
    {
      title: '操作',
      dataIndex: 'operation',
      render: (text, record) => {
        return (
          <span className={styles.one}>
            {isMenuVisible('system:menu:edit') && (
              <a
                onClick={() => {
                  this.handleEditor(record);
                }}
              >
                编辑
              </a>
            )}
            {isMenuVisible('system:menu:delete') && (
              <a
                onClick={() => {
                  this.handleSigDelete(record);
                }}
              >
                删除
              </a>
            )}
          </span>
        );
      },
    },
  ];
  render() {
    const { userStatus } = this.state;
    const { getFieldDecorator } = this.props.form;
    const formItemLayout = {
      wrapperCol: { span: 16 },
    };
    const title = this.state.isAdd ? '新增菜单' : '编辑菜单';
    return (
      <div className={`${styles.container} ${styles.menuManager}`}>
        <div className={styles.userRight}>
          <div style={{ overflow: 'hidden' }}>
            <div className={styles['inforAnasy-container-top-btn']}>
              {isMenuVisible('system:menu:add') && (
                <Button type="link" onClick={this.handleAddDept}>
                  <Icon type="plus" />
                  新增
                </Button>
              )}
              <Button type="link" onClick={this.handleUnfold}>
                {/* <Icon type="plus" /> */}
                展开
              </Button>
              <Button type="link" onClick={this.handleUpTree}>
                {/* <Icon type="plus" /> */}
                折叠
              </Button>
            </div>
            <div>
              <div className={styles['dev-search-select']}>
                <Input
                  value={this.state.filterQueryParams.menuName}
                  onChange={this.handleChange}
                  addonBefore="菜单名称"
                  type="text"
                />
              </div>
              <div className={styles['dev-search-select']}>
                <span className={styles['dev-search-select-title']}>菜单状态</span>
                <Select
                  defaultValue="请选择"
                  style={{ width: 200 }}
                  onChange={this.handleChangeStatus}
                  value={this.state.filterQueryParams.visible}
                >
                  <Option value="">所有</Option>
                  {_.map(userStatus, (item: any, index: number) => (
                    <Option key={index} value={item.dictValue}>
                      {item.dictLabel}
                    </Option>
                  ))}
                </Select>
              </div>
              {isMenuVisible('system:menu:queryByList') && (
                <Button
                  type="link"
                  className={styles['search']}
                  onClick={() => {
                    this.setState(
                      produce((draft: Draft): void => {
                        draft.filterQueryParams.pageNum = 1;
                      }),
                      () => {
                        this.handleFilterQuery();
                      },
                    );
                  }}
                >
                  搜索
                </Button>
              )}
              <Button
                type="link"
                className={styles['search']}
                onClick={() => {
                  this.setState(
                    produce((draft: Draft): void => {
                      draft.filterQueryParams.menuName = '';
                      draft.filterQueryParams.visible = undefined;
                    }),
                  );
                }}
              >
                重置
              </Button>
            </div>
          </div>
          <Table
            scroll={{ y: '500px' }}
            pagination={false}
            columns={this.columns}
            dataSource={this.state.menuList}
            rowKey="menuId"
            expandedRowKeys={this.state.expandedRowsKeys}
            onExpand={this.handleOnExpand}
          />
          {/* <div className="pagination-box"> */}
          {/* <Pagination defaultCurrent={this.state.filterQueryParams.pageNum} current={this.state.filterQueryParams.pageNum} onChange={this.handlePageChange} total={this.state.deptList.total} /> */}
          {/* <span className="pagination-title-box">
              第{this.state.filterQueryParams.pageNum}/
              {Math.ceil(this.state.deptList.total / this.state.filterQueryParams.pageSize)}页 共
              {this.state.deptList.total}条
            </span> */}
          {/* </div> */}
          <Modal
            title={title}
            visible={this.state.showModel}
            className="userModal_box menuModal_box"
            onCancel={() => {
              this.props.form.resetFields();
              this.setState({ showModel: false, addChecked: true });
              this.setState({ selectedKeys: [] });
            }}
          >
            <Form className="ant-advanced-search-form">
              <Form.Item {...formItemLayout} label="上级菜单">
                {getFieldDecorator('parentName', {
                  initialValue: this.state.parentName,
                  rules: [{ required: false, message: '请选择上级菜单' }],
                })(
                  <Input
                    type="text"
                    placeholder="请选择上级菜单"
                    readOnly={true}
                    onClick={this.menuParent}
                  />,
                )}
              </Form.Item>
              {this.state.isAdd ? null : (
                <Form.Item {...formItemLayout} label="菜单Id" style={{ display: 'none' }}>
                  {getFieldDecorator('menuId', {
                    rules: [{ required: true, message: '请输入菜单Id' }],
                  })(<Input type="text" placeholder="请输入菜单Id" />)}
                </Form.Item>
              )}
              {this.state.isAdd ? (
                <Form.Item {...formItemLayout} label="系统Id:" style={{ display: 'none' }}>
                  {getFieldDecorator('systemId', {
                    initialValue: localStorage.getItem('surSystemId'),
                    rules: [{ required: false }],
                  })(<Input placeholder="请输入系统Id" />)}
                </Form.Item>
              ) : null}
              <Form.Item {...formItemLayout} label="菜单类型">
                {getFieldDecorator('menuType', {
                  initialValue: 'M',
                  rules: [{ required: true, message: '请选择菜单类型' }],
                })(
                  <Radio.Group>
                                  <Radio value="M">目录</Radio>
                                  <Radio value="C">菜单</Radio>
                    <Radio value="F">按钮</Radio>
                  </Radio.Group>,
                )}
                  
              </Form.Item>
              <Form.Item {...formItemLayout} label="菜单名称">
                {getFieldDecorator('menuName', {
                  rules: [
                    { required: true, message: '请输入菜单名称' },
                    {
                      max: 20,
                      message: '最多输入20位中文名',
                    },
                  ],
                })(<Input type="text" placeholder="请输入菜单名称" maxLength={20} />)}
              </Form.Item>
              {/* <Form.Item {...formItemLayout} label="请求地址">
                {getFieldDecorator('path', {
                  rules: [
                    {
                      required: true,
                      message: '请输入请求地址',
                    },
                  ],
                })(<Input placeholder="请输入请求地址" />)}
              </Form.Item> */}
              <Form.Item {...formItemLayout} label="权限标识">
                {getFieldDecorator('perms', {
                  rules: [
                    { required: true, message: '请输入权限标识' },
                    {
                      max: 30,
                      message: '最多输入30位字符',
                    },
                  ],
                })(<Input placeholder="请输入权限标识" maxLength={30} />)}
              </Form.Item>
              <Form.Item {...formItemLayout} label="显示排序">
                {getFieldDecorator('orderNum', {
                  rules: [
                    {
                      required: false,
                      pattern: new RegExp(/^[0-9]\d*$/, 'g'),
                      message: '请输入数字!',
                    },
                    {
                      max: 10,
                      message: '最多输入10位数字',
                    },
                  ],
                })(<Input placeholder="请输入显示排序" />)}
              </Form.Item>
              <Form.Item {...formItemLayout} label="菜单状态">
                {getFieldDecorator('visible', {
                  initialValue: true,
                  rules: [{ required: false }],
                })(
                  <Switch
                    defaultChecked={true}
                    checked={this.state.isAdd ? this.state.addChecked : this.state.isChecked}
                    onChange={this.onSwitchChange}
                  />,
                )}
              </Form.Item>
            </Form>
            <div className={styles.footBtnArea}>
              <div
                style={{ marginRight: '30px' }}
                className={styles.foot_btn}
                onClick={this.handleSubmit}
              >
                确定
              </div>
              <div
                className={styles.foot_btn}
                onClick={() => {
                  this.setState({ showModel: false, addChecked: true });
                  this.props.form.resetFields();
                }}
              >
                取消
              </div>
            </div>
          </Modal>
          <Modal
            title="系统提示"
            className={styles.modal}
            visible={this.state.isTrue}
            onCancel={() => {
              this.setState({ isTrue: false });
            }}
          >
            <div className={styles.titles}>{this.state.title}</div>
            <div className={styles.footBtn}>
              <div
                style={{ marginRight: '30px' }}
                className={styles.foot_btn}
                onClick={this.handleSure}
              >
                确定
              </div>
              <div
                className={styles.foot_btn}
                onClick={() => {
                  this.setState({ selectedKeys: [] });
                  this.setState({ isTrue: false });
                }}
              >
                取消
              </div>
            </div>
          </Modal>
          <Modal
            title="菜单选择"
            className={`${styles.modal} ${styles.menu}`}
            visible={this.state.isMenuShow}
            onCancel={() => {
              this.setState({ isMenuShow: false });
              this.setState({ selectedKeys: [] });
            }}
          >
            <div className={styles.treeNode}>
              <Tree
                onExpand={this.onExpand}
                expandedKeys={this.state.expandedKeys}
                autoExpandParent={this.state.autoExpandParent}
                onSelect={this.onSelect}
                selectedKeys={this.state.selectedKeys}
              >
                {this.renderTreeNodes(this.state.parentMenu)}
              </Tree>
            </div>
            <div className={styles.footBtn}>
              <div
                style={{ marginRight: '30px' }}
                className={styles.foot_btn}
                onClick={this.handleMenu}
              >
                确定
              </div>
              <div
                className={styles.foot_btn}
                onClick={() => {
                  this.setState({ isMenuShow: false });
                  this.setState({ selectedKeys: [] });
                }}
              >
                取消
              </div>
            </div>
          </Modal>
        </div>
      </div>
    );
  }
}
export default Form.create<menuPsops>()(menuManage);
